package com.example.stray_animal_management_system.admin.Statistics;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.stray_animal_management_system.entity.User;
import com.example.stray_animal_management_system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description:
 * @author: panpan
 * @time: 2025/11/7
 */
@RestController
@RequestMapping("/api/admin/statistics")
public class StatisticsController {

    @Autowired
    private UserService userService;

    /**
     * 获取所有用户数量
     */
    @GetMapping("/userCount")
    public Map<String, Object> getUserCount() {
        Map<String, Object> res = new HashMap<>();
        long count = userService.count();  // 获取所有用户数
        res.put("code", 200);
        res.put("data", count);
        return res;
    }

    /**
     * 按状态统计用户数量
     */
    @GetMapping("/userStatusCount")
    public Map<String, Object> getUserStatusCount() {
        Map<String, Object> res = new HashMap<>();

        // 使用 QueryWrapper 执行原生 SQL 查询
        List<Map<String, Object>> statusCount = userService.getBaseMapper()
                .selectMaps(new QueryWrapper<User>()
                        .select("status, COUNT(*) as count")  // 使用原生 SQL 查询
                        .groupBy("status")  // 按 status 分组
                );

        res.put("code", 200);
        res.put("data", statusCount);
        return res;
    }

    /**
     * 按角色统计用户数量
     */
    @GetMapping("/userRoleCount")
    public Map<String, Object> getUserRoleCount() {
        Map<String, Object> res = new HashMap<>();

        // 使用 QueryWrapper 执行原生 SQL 查询
        List<Map<String, Object>> roleCount = userService.getBaseMapper()
                .selectMaps(new QueryWrapper<User>()
                        .select("role_id, COUNT(*) as count")  // 使用原生 SQL 查询
                        .groupBy("role_id")  // 按 role_id 分组
                );

        res.put("code", 200);
        res.put("data", roleCount);
        return res;
    }

}
